<?php 
namespace xfyzf\admin\controller;
use lib\Commontc;
use lib\XFDB;
class Admin{
 
    public function index(){
         global $islogin_admin,$conf;
         if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
         include admintem.'index.php';
    }
    public function login(){
        global $islogin_admin,$conf;
        if(isset(input('get')['logout'])){
        	setcookie("admin_token", "", time() - 99999999999999999);
        	@header('Content-Type: text/html; charset=UTF-8');
        	Commontc::truetc("注销成功！",rethreffun('./login'));
        }
         if($islogin_admin == '1')Commontc::truetc("您已登录！",rethreffun('./index'));
         include admintem.'login.php';
    }
    public function main(){
        global $islogin_admin,$conf;
         if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
         $sql = "select VERSION() as ver ";
        $DB_VERSION = executeSQLQuery($sql)['ver'];
         include admintem.'main.php';
    }
    public function site(){
        global $islogin_admin,$conf;
        if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        if (input('get')['a'] == "upLoad") {
            if (copy($_FILES['file']['tmp_name'], ROOT . '/Core/assets/img/logo.png')) {
                exitjson(200,'上传成功');
            } else {
                exitjson(500,'上传Logo失败');
            }
        }
        include admintem.'site.php';
    }
    public function template(){
         global $islogin_admin,$conf;
        if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        if(input("get")['a']){
             header("Content-Type: application/json");
            $mblist = \lib\Template::getList();
            $data = [];
            foreach ($mblist as $k => $v) {
                $data[] = ["id" => ($k + 1), "title" => $v, "image" => "\../Template/" . $v . "/preview.png", "remark" => "", "time" => "V9.9.9"];
            }
            exit(json_encode(['msg' => "not data","count" => count($mblist), "data" => $data, "code" => 0, ], 320));
        }
         include admintem.'template.php';
    }
    public function logintemplate(){
        global $islogin_admin,$conf;
        if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        if(input("get")['a']){
             header("Content-Type: application/json");
            $mblist = \lib\LoginTemplate::getList();
            $data = [];
            foreach ($mblist as $k => $v) {
                $data[] = ["id" => ($k + 1), "title" => $v, "image" => "\../User/template/" . $v . "/preview.png", "remark" => "", "time" => "V9.9.9"];
            }
            exit(json_encode(['msg' => "not data","count" => count($mblist), "data" => $data, "code" => 0, ], 320));
        }
         include admintem.'logintemplate.php';
    }
   public function pay(){
        global $islogin_admin,$conf;
        if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        include admintem.'pay.php';
   }
   public function pay_meal(){
        global $islogin_admin,$conf;
        if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        $meals = json_decode($conf['pay_meal'], true);
        if (!is_array($meals)) $meals = [];
        include admintem.'pay_meal.php';
   }
   public function SetNotice(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        include admintem.'SetNotice.php';
   }
   public function mail(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       include admintem.'mail.php'; 
   }
   public function Order(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       include admintem.'Order.php'; 
   }
   public function consume(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        $lastday = date("Y-m-d", strtotime("-1 day"));
        $today = date("Y-m-d");
        $currentYear = date("Y");
        $currentMonth = date("m");
        // 计算本月的第一天和最后一天
        $firstDayOfMonth = date("Y-m-01", strtotime("$currentYear-$currentMonth-01"));
        $lastDayOfMonth = date("Y-m-t", strtotime("$currentYear-$currentMonth-01"));
         //年
         $currentYear = date("Y");
         // 构造当天开始时间（即0点）
        $startTime = $today . " 00:00:00";
        $endTime = $today . " 23:59:59";
        // 昨天的开始时间
        $startTimeYesterday = $lastday . " 00:00:00";
        // 昨天的结束时间
        $endTimeYesterday = $lastday . " 23:59:59";
        $sql = "SELECT COUNT(*) as count FROM pay_order";  
        $count1 = executeSQLQuery($sql)['count'];
        $sql = "SELECT COUNT(*) as count FROM pay_user";
        $count2 = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist";
        $count3 = executeSQLQuery($sql)['count'];
        $sql = "SELECT sum(money) as count from pay_order WHERE status='1'";
        $count4 = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist where status='1' and type='qqpay'";
        $qqpay_cookie_on = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist where status='1' and type='wxpay'";
        $wxpay_cookie_on = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist where status='1' and type='alipay'";
        $alipay_cookie_on = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist where status='1' and type='usdtpay'";
        $usdtpay_cookie_on = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist where status!='1' and type='qqpay'";
        $qqpay_cookie_ok = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist where status!='1' and type='wxpay'";
        $wxpay_cookie_ok = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_qrlist where status!='1' and type='alipay'";
        $alipay_cookie_ok = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count FROM pay_order WHERE addtime >= '$startTime' AND addtime <= '$endTime' AND status = 1"; // 已付款订单数量
        $todayPayOrder = executeSQLQuery($sql)['count'];
        $sql = "SELECT COALESCE(SUM(money), 0) as count from pay_order WHERE status=1 and addtime >= '$startTime' AND addtime <= '$endTime' ";// 已付款金额
        $todayPayMoney = executeSQLQuery($sql)['count'];
        $sql = "SELECT count(*) as count from pay_order WHERE addtime >= '$startTime' AND addtime <= '$endTime'";// 订单总数
        $todayOrderTotal = executeSQLQuery($sql)['count'];
        $sql = "SELECT COALESCE(SUM(money), 0) as count from pay_order WHERE addtime >= '$startTime' AND addtime <= '$endTime'";// 未/已付款金额
        $todayPayAllMoney = executeSQLQuery($sql)['count'];
        if ($todayOrderTotal > 0) {
            $successRate = ($todayPayOrder / $todayOrderTotal) * 100;
        } else {
            $successRate = 0; // 避免除以零错误
        }
        $todayPaySuccess = number_format($successRate, 2); // 付款成功率
        
        $sql = "SELECT COUNT(*) as count FROM pay_order WHERE status='1' and addtime >= '$firstDayOfMonth' AND addtime <= '$lastDayOfMonth'";//已付款订单量
        $monthPayOrder = executeSQLQuery($sql)['count'];
        $sql = "SELECT COALESCE(SUM(money), 0) as count FROM pay_order WHERE addtime >= '$firstDayOfMonth' AND addtime <= '$lastDayOfMonth' AND status = 1";//已付金额
        $monthPayMoney =  executeSQLQuery($sql)['count'];
        $sql = "SELECT COUNT(*) as count FROM pay_order WHERE  addtime >= '$firstDayOfMonth' AND addtime <= '$lastDayOfMonth'";//订单总数
        $monthOrderTotal = executeSQLQuery($sql)['count'];
        $sql = "SELECT COALESCE(SUM(money), 0) as count  FROM pay_order WHERE addtime >= '$firstDayOfMonth' AND addtime <= '$lastDayOfMonth'";
        $monthPayAllMoney = executeSQLQuery($sql)['count'];
         if ($monthOrderTotal > 0) {
                $monthPaySuccess = ($monthPayOrder / $monthOrderTotal) * 100;
            } else {
               $monthPaySuccess = 0; // 避免除以零错误
            }
         $monthPaySuccess = number_format($monthPaySuccess, 2); 
         $sql = "SELECT COUNT(*) as count FROM pay_order WHERE status = 1 AND YEAR(addtime) = '$currentYear'";
        $yearPayOrder = executeSQLQuery($sql)['count'];
        $sql = "SELECT COALESCE(SUM(money), 0) as count FROM pay_order WHERE YEAR(addtime) = '$currentYear' AND status = 1";
        $yearPayMoney = executeSQLQuery($sql)['count'];
        $sql = "SELECT COUNT(*) as count FROM pay_order WHERE YEAR(addtime) = '$currentYear'";
        $yearOrderTotal = executeSQLQuery($sql)['count'];
        $sql = "SELECT COALESCE(SUM(money), 0) as count FROM pay_order WHERE  YEAR(addtime) = '$currentYear'";
        $yearPayAllMoney = executeSQLQuery($sql)['count'];
        if ($yearOrderTotal > 0) {
            $yearPaymentSuccessRate = ($yearPayOrder / $yearOrderTotal) * 100;
        } else {
            $yearPaymentSuccessRate = 0; // 避免除以零错误
        }
        $yearPaySuccess = number_format($yearPaymentSuccessRate, 2); // 付款成功率
        $order = [];
        $paymentTypes = ['wxpay', 'alipay', 'qqpay', 'usdtpay','all'];
        foreach ($paymentTypes as $type){
            $sql1 = '';
            if($type!='all')$sql1 = "AND `type`='$type'";
             $sql = "SELECT count(*) as count FROM pay_order WHERE addtime >= '$startTime' AND addtime <= '$endTime' $sql1 AND `status` ='1'";
             $order[$type]['todayOrder'] = executeSQLQuery($sql)['count'];
            $sql = "SELECT SUM(money) as count FROM pay_order WHERE addtime >= '$startTime' AND addtime <= '$endTime' $sql1 AND status ='1'";
            $order[$type]['todayOrdermoney'] = executeSQLQuery($sql)['count'];
            
            $sql = "SELECT count(*) as count FROM pay_order WHERE addtime >= '$startTimeYesterday' AND addtime <= '$endTimeYesterday' $sql1 AND status ='1'";
            $order[$type]['lastday'] = executeSQLQuery($sql)['count'];
            
            $sql = "SELECT SUM(money) as count FROM pay_order WHERE addtime >= '$startTimeYesterday' AND addtime <= '$endTimeYesterday' $sql1 AND status ='1'";
            $order[$type]['lastdaymoney'] = executeSQLQuery($sql)['count'];
            
            $todayOrder = $order[$type]['todayOrder'];
            $lastDayOrder = $order[$type]['lastday']; 
            if ($lastDayOrder > 0) {
                $growthRate = (($todayOrder - $lastDayOrder) / $lastDayOrder) * 100;
            } else {
                // 如果昨天的订单数量为0，直接设置增长率为今天的订单数量（因为不能除以0）
                // 或者可以设置为无限大，或者根据实际情况处理
                $growthRate = $todayOrder > 0 ? 100 : 0; // 如果今天有订单，且昨天为0，则增长率为无穷大，否则为0
            }
            
            $order[$type]['t'] = sprintf("%.2f", $growthRate);
        }
        
       include admintem.'consume.php';
   } 
   public function User(){
        global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my'] ?? "list";
       $id = explode("/",input("get")['id'])[0];
       if(!empty($id) && $my == 'edit'){
           $sql = "SELECT * FROM  pay_user where pid = '$id' limit 1";
           $row = executeSQLQuery($sql);
       }
       include admintem.'User.php';
   }
   public function Qrlist(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       include admintem.'Qrlist.php';
       
   }
   public function Package(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my'] ?? "list";
       $id = input("get")['id'];
       if(!empty($id) && $my == 'edit'){
           $sql = "SELECT * FROM  pay_package where id = '$id' limit 1";
           $row = executeSQLQuery($sql);
       }
       include admintem.'Package.php';
   }
   public function pay_vip(){
        global $islogin_admin,$conf;
        if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        include admintem.'pay_vip.php';
   }
   public function Wechat_Trumpet(){
       global $islogin_admin,$conf,$httphost;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my'] ?? "list";
       $id = input("get")['id']??"";
       if(!empty($id) && $my == 'edit'){
           $sql = "SELECT * FROM  pay_wechat_trumpet where id = '$id' limit 1";
           $row = executeSQLQuery($sql);
       }
       $token = json_encode(array("pid"=>$conf['admin_user'],"key"=>$conf['admin_pass']));
       $token= aes256auth($token,wxpcadmindytxtokenkey);
       include admintem.'Wechat_Trumpet.php';
   }
   public function Risk(){
       global $islogin_admin;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       include admintem.'Risk.php';
   }
   public function Log(){
       global $islogin_admin;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       include admintem.'Log.php';
   }
   public function cron(){
       global $islogin_admin,$httphost,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
        include admintem.'cron.php';
   }
   public function Notice(){
       global $islogin_admin;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my'] ?? 'list';
       $id = input("get")['id'] ?? '';
       
       if(!empty($id) && $my == 'edit'){
           
           $sql = "SELECT * FROM  pay_notice where id = '$id' limit 1";
           $row = executeSQLQuery($sql);
       }
       include admintem.'Notice.php';
   }
   public function down(){
       global $islogin_admin;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my'] ?? 'list';
       $id = input("get")['id'] ?? '';
       if(!empty($id) && $my == 'edit'){
           $sql = "SELECT * FROM  pay_down where id = '$id' limit 1";
           $row = executeSQLQuery($sql);
       }
       include admintem.'down.php';
   }
   public function Work(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my'] ?? 'list';
       $id = input("get")['id']??'';
       if(!empty($id) && $my == 'edit'){
            $sql="SELECT * FROM  pay_work where id = '$id' limit 1";
            $row = executeSQLQuery($sql); 
            $readonly = !empty($row['huifu']) ? 'readonly' : '';
             $class = !empty($row['huifu']) ? 'layui-textarea layui-form-danger' : 'layui-textarea';
        }
       include admintem.'Work.php';
   }
   public function Update(){
       global $islogin_admin;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $url = XFAPI_URL . '/api_check.php?url=' . $_SERVER['HTTP_HOST'] . '&authcode=' . xfauthcode . '&ver=' . Version . '&cxid=' . xfcxid;
       
       $url1= XFAPI_URL.'/gx.php?act=api&cxid='.xfcxid."&url=".$_SERVER['HTTP_HOST'];
       $uplog= get_curl($url1);
       $upjson=json_decode($uplog,true);
       if($upjson['code'] == 1){
           $uplogtxt=nl2br(html_entity_decode($upjson['data']['sql_up_log']));
           $newup=$upjson['data']['sql_grade'];
       }
       $result = get_curl($url);
       
      $res = json_decode($result, true); 
      if(!$res['msg'])$res['msg']='啊哦，更新服务器开小差了，请刷新此页面。';
      if($res['code'] == '1'){
        if(!class_exists('ZipArchive') || ini_get('acl.app_id') || defined("SAE_ACCESSKEY") || defined("BAE_ENV_APPID")) {
        // echo '您的空间不支持自动更新，请手动下载更新包并覆盖到程序根目录！<br/>
        // 更新包下载：<a href="'.$res['file'].'" class="btn btn-primary">update.zip('.$Version.')</a>';
        }else{
            if($res['anniu']){
             $anniu=$res['anniu'];
            }else{
              $anniu='立即更新到最新版本'; 
            }
        }
    }else{
        $anniu = '暂无更新包';
    }
    if (is_writable('./')){
	    $kedu= '<font color="green">可用√</font>'; 
	}else{
	    $kedu= '<font color="black">不支持</font>';
	} 
       include admintem.'Update.php';
   }
   public function account(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       include admintem.'account.php';  
   }
   public function meihua(){
        global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       include admintem.'meihua.php'; 
   }
   public function qunemail(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my']??'list';
       
       include admintem.'qunemail.php'; 
   }
   public function wxyunurl(){
       global $islogin_admin,$conf;
       if($islogin_admin!='1')Commontc::falsetc("请先登录",rethreffun('./login'));
       $my = input("get")['my']??'list';
       $id = input("get")['id']??'';
       if($my == 'edit' && !empty($id)){
           $row = XFDB::wxyunurlrow($id);
           
       }
       include admintem.'wxyunurl.php'; 
   }
}
?>